import {
  ForbiddenException,
  Injectable,
  NotFoundException,
  UnauthorizedException,
} from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import * as crypto from 'crypto';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}
  async signIn(signInDto: CreateAuthDto) {
    try {
      const user = await this.userService.findOne({
        username: signInDto.username,
      });
      const md5 = crypto.createHash('md5');
      const hashedPsd = md5.update(signInDto.password).digest('hex');
      if (user.password !== hashedPsd) {
        throw new UnauthorizedException('账户和密码不对');
      }
      const token = await this.jwtService.signAsync({
        username: signInDto.username,
        userId: user.id,
      });
      return {
        token,
        userId: user.id,
      };
    } catch {
      throw new ForbiddenException('请先注册');
    }
  }

  async signUp(signUpDto: CreateAuthDto) {
    const user = await this.userService.findOne({
      username: signUpDto.username,
    });
    if (user) {
      throw new ForbiddenException('当前用户已注册');
    } else {
      return this.userService.create(signUpDto);
    }
  }
}
